<template>
  <div class="divBox">
    <el-card class="box-card" shadow="never">
      <el-form
        ref="formConf"
        v-loading="loading"
        :model="formConf"
        :rules="ruleValidate"
        class="formValidate mt20"
        label-width="150px"
        @submit.native.prevent
      >
        <el-col :span="13">
          <el-form-item
            label="直播间名称："
            prop="name"
          >
            <el-input
              v-model="formConf.name"
              maxlength="50"
              placeholder="请输入直播间名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="主播名称：" prop="anchorsName">
            <el-input
              v-model="formConf.anchorsName"
              maxlength="50"
              placeholder="请输入主播名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="主播头像：" prop="anchoravatar">
            <div v-if="formConf.anchoravatar==''" class="upLoadPicBox" @click="modalPicTap(4)">
              <div class="upLoad">
                <i class="el-icon-camera cameraIconfont"/>
              </div>
            </div>
            <div v-else class="pictrue">
              <img :src="formConf.anchoravatar" @click="modalPicTap(4)"/>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="开播时间：" prop="scheduleTime">
            <el-date-picker
              v-model="formConf.scheduleTime"
              placeholder="请选择开播时间"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="onchangeTime"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="直播间有效期：" prop="expireTime">
            <el-date-picker
              v-model="formConf.expireTime"
              placeholder="请选择直播间有效期"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
            <el-tooltip
              class="item"
              content="建议比直播结束时间多延迟一天"
              effect="dark"
              placement="right"
            >
              <i class="el-icon-question" style="margin-left: 10px;color:#8a8a8a"></i>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="直播间封面：" prop="cover">
            <div v-if="formConf.cover==''" class="upLoadPicBox" @click="modalPicTap(2)">
              <div class="upLoad">
                <i class="el-icon-camera cameraIconfont"/>
              </div>
            </div>
            <div v-else class="pictrue">
              <img :src="formConf.cover" @click="modalPicTap(2)"/>
            </div>
            <div style="color:#8a8a8a">建议直播间封面图大小为367*160</div>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="直播间背景图：" prop="background">
            <div v-if="formConf.background==''" class="upLoadPicBox" @click="modalPicTap(3)">
              <div class="upLoad">
                <i class="el-icon-camera cameraIconfont"/>
              </div>
            </div>
            <div v-else class="pictrue">
              <img :src="formConf.background" @click="modalPicTap(3)"/>
            </div>
            <div style="color:#8a8a8a">建议直播间背景图大小比例为9:16(1080*1920)</div>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="短视频：" prop="assistantsavatar">
            <div v-if="formConf.coverVideo==null" class="upLoadPicBox" @click="modalPicTap(6)">
              <div class="upLoad">
                <i class="el-icon-video-camera cameraIconfont"/>
              </div>
            </div>
            <div v-else class="pictrue">
              <video :src="formConf.coverVideo" @click="modalPicTap(6)"></video>
            </div>
            <div style="color:#8a8a8a">建议直播间短视频为 .mp4 的视频</div>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="助理名称：" prop="assistantsname">
            <el-input
              v-model="formConf.assistantsname"
              maxlength="50"
              placeholder="请输入助理名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="助理头像：" prop="assistantsavatar">
            <div v-if="formConf.assistantsavatar==null" class="upLoadPicBox" @click="modalPicTap(5)">
              <div class="upLoad">
                <i class="el-icon-camera cameraIconfont"/>
              </div>
            </div>
            <div v-else class="pictrue">
              <img :src="formConf.assistantsavatar" @click="modalPicTap(5)"/>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="开启邀请奖励：" prop="enableInviteReward">
            <el-switch v-model="formConf.enableInviteReward" @change="startInviteReward">
            </el-switch>
          </el-form-item>
        </el-col>
        <el-col v-if="formConf.enableInviteReward" :span="24">
          <el-form-item v-for="(item, index) in ruleList" :key="index" class="inviteReward-rule">
            <el-input v-model="item.startNumber" placeholder="起始人数" type="number" @blur="numberfilter(item)"
            ></el-input>
            <el-input v-model="item.endNumber" placeholder="结束人数" type="number" @blur="numberfilter(item)"
            ></el-input>
            <el-button plain @click="selectRewards(index)">
              {{
                item.rewardList && item.rewardList.length > 0 ? '查看/变更已选择奖品(' + item.rewardList.length + ')' : '选择奖品'
              }}
            </el-button>
            <el-button v-if="index === 0" @click="addRules()">
              <i class="el-icon-plus"></i>
            </el-button>
            <el-button v-if="index !== 0" @click="removeRules(index)">
              <i class="el-icon-minus"></i>
            </el-button>
            <div v-if="item.rewardList" class="rewardList">
              <span v-for="item in item.rewardList">{{ item.name }}({{ item.quantity }}件);</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24" style="padding: 0 0 20px 120px">
          <el-button class="submission" type="primary" @click="submit('formConf')"
          >提交
          </el-button
          >
        </el-col>
      </el-form>
    </el-card>
    <el-dialog :before-close="inviteBeforeClose" :visible.sync="inviteVisible" title="商品列表" top="80px" width="60%">
      <el-table
        ref="multipleTable"
        v-loading="inviteLoading"
        :data="inviteTableData"
        :row-key="getRowKeys" size="mini"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column :reserve-selection="true" type="selection"></el-table-column>
        <el-table-column
          label="ID"
          min-width="50"
          prop="id"
        />
        <el-table-column label="商品图" width="80">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                :preview-src-list="[scope.row.cover]"
                :src="scope.row.cover"
                style="width: 36px; height: 36px"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="商品名称"
          min-width="150"
          prop="name"
        />
        <el-table-column
          label="商品规格"
          min-width="100"
          prop="attrValues"
        />
        <el-table-column
          label="商品价格"
          prop="price"
          width="100"
        />
        <el-table-column
          label="商品分类"
          width="200"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.cateValues==null">-</span>
            <div v-else>
              <span v-for="(item, index) in scope.row.cateValues.split(',')" :key="index" class="mr10">{{ item }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="奖品数量"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.quantity" @blur="inviteQuantity(scope.row.id, scope.row.quantity)"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="inviteCurrent"
        :total="inviteTotal"
        layout="total, prev, pager, next, jumper"
        @current-change="pageChange"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="inviteEvent('can')">取 消</el-button>
        <el-button type="primary" @click="inviteEvent('sub')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getmeizhiInfo, getmeizhiupdata } from '@/api/marketing.js'
import { skuproductLstApi } from '@/api/store.js'

export default {
  name: 'Config',
  data() {
    return {
      loading: false,
      handleNum: 'many',
      // 表单
      formConf: {
        id: null,
        title: '', //直播间名称
        scheduleTime: '', //开始时间
        expireTime: '', //推流有效期
        name: '', //标题
        anchorsName: '',//主播名
        anchoravatar: '',//主播头像
        assistantsname: null,//助理名
        assistantsavatar: null,//助理头像
        cover: '',//封面图
        background: '',//背景图
        enableInviteReward: false, // 开启邀请奖励
        coverVideo: null
      },
      ruleList: [],
      isShow: true,
      ruleValidate: {
        name: [
          { required: true, message: '请输入直播间名称', trigger: 'blur' }
        ],
        anchorsName: [
          { required: true, message: '请输入主播名称', trigger: 'blur' }
        ],
        anchoravatar: [
          {
            required: true,
            message: '请上传直播封面',
            trigger: 'change'
          }
        ],
        cover: [
          {
            required: true,
            message: '请上传直播封面',
            trigger: 'change'
          }
        ],
        background: [
          {
            required: true,
            message: '请上传直播背景图',
            trigger: 'change'
          }
        ],
        scheduleTime: [
          {
            required: true,
            message: '请选择开播时间',
            trigger: 'change'
          }
        ],
        expireTime: [
          {
            required: true,
            message: '请选择推流到期时间',
            trigger: 'change'
          }
        ]
      },
      inviteVisible: false,
      inviteTableData: [],
      inviteTotal: 0,
      inviteCurrent: 1,
      inviteLoading: false,
      multipleSelection: [],
      getRowKeys(row) {
        return row.id
      },
      inviteSelectIndex: 0
    }
  },
  created() {
    if (window.location.search.split('=')[1]) {
      this.id = window.location.search.split('=')[1]
      this.getFormInfo()
    }
    console.log(this.id)
  },
  methods: {
    inviteEvent(type) {
      if (type === 'can') {
        this.inviteVisible = false
        this.$refs.multipleTable.clearSelection()
      }
      if (type === 'sub') {
        this.inviteBeforeClose()
      }
    },
    // 关闭弹窗前判断
    inviteBeforeClose() {
      let hasQuantity = true
      this.multipleSelection.map(item => {
        if (item.quantity === '') {
          hasQuantity = false
        }
      })
      if (hasQuantity) {
        this.ruleList[this.inviteSelectIndex].rewardList = JSON.parse(JSON.stringify(this.multipleSelection))
        this.$refs.multipleTable.clearSelection()
        this.inviteVisible = false
      } else {
        this.$message.warning('请检查已选择奖品的数量')
        return false
      }
    },
    inviteQuantity(id, quantity) {
      this.multipleSelection.map(item => {
        if (id === item.skuId) {
          item.quantity = quantity
        }
      })
    },
    // 选中奖品
    handleSelectionChange(val) {
      const tables = []
      val.map((item) => {
        tables.push({
          name: item.name,
          quantity: item.quantity ? item.quantity : '',
          skuId: item.id
        })
      })
      this.multipleSelection = tables
    },
    // 开启邀请奖励
    startInviteReward(value) {
      if (value) {
        this.ruleList.push({
          startNumber: '',
          endNumber: ''
        })
      } else {
        this.ruleList = []
      }
    },
    // 打开奖品弹窗
    selectRewards(value) {
      this.inviteSelectIndex = value
      this.inviteVisible = true
      this.getProduct()
    },
    // 选择奖品
    getProduct(type) {
      let info = {
        page: this.inviteCurrent, limit: 10,
        keywords: ''
      }
      this.inviteLoading = true
      skuproductLstApi(info).then(params => {
        this.inviteTableData = params.records
        this.inviteTotal = params.total
        // 判断是否已有选择的奖品
        if (type === 'pageChange') {
          if (this.multipleSelection) {
            console.log(this.multipleSelection)
            this.inviteTableData.forEach(item => {
              this.multipleSelection.forEach(element => {
                if (Number(item.id) === Number(element.skuId)) {
                  this.$set(item, 'quantity', Number(element.quantity))
                  this.$nextTick(() => {
                    this.$refs.multipleTable.toggleRowSelection(item, true)
                  })
                }
              })
            })
          }
        } else {
          if (this.ruleList[this.inviteSelectIndex].rewardList) {
            this.inviteTableData.forEach(item => {
              this.ruleList[this.inviteSelectIndex].rewardList.forEach(element => {
                if (Number(item.id) === Number(element.skuId)) {
                  this.$nextTick(() => {
                    item.quantity = element.quantity
                    this.$refs.multipleTable.toggleRowSelection(item, true)
                  })
                }
              })
            })
          }
        }
        this.inviteLoading = false
      })
    },
    pageChange(current) {
      this.inviteCurrent = current
      this.getProduct('pageChange')
    },
    // 新增规则
    addRules() {
      this.ruleList.push({
        startNumber: '',
        endNumber: ''
      })
    },
    // 删除规则
    removeRules(index) {
      this.ruleList.splice(index, 1)
    },
    // 起始人数和结束人数判断
    numberfilter(item) {
      if (item.startNumber && item.endNumber) {
        if (item.startNumber >= item.endNumber) {
          item.startNumber = item.endNumber - 1
        }
      }
    },
    //添加轮播图
    modalPicTap(tit, num, i) {
      const _this = this
      // _this.formConf.cover=[]
      this.$modalUpload(
        function(img) {
          if (tit === 2 && !num) {
            if (img.length > 1) {
              return this.$message.warning('最多选择1张图片！')
            } else {
              _this.formConf.cover = img[0].sattDir
            }
          } else if (tit === 3 && !num) {
            if (img.length > 1) {
              return this.$message.warning('最多选择1张图片！')
            } else {
              _this.formConf.background = img[0].sattDir
            }
          } else if (tit === 4 && !num) {
            if (img.length > 1) {
              return this.$message.warning('最多选择1张图片！')
            } else {
              _this.formConf.anchoravatar = img[0].sattDir
            }
          } else if (tit === 5 && !num) {
            if (img.length > 1) {
              return this.$message.warning('最多选择1张图片！')
            } else {
              _this.formConf.assistantsavatar = img[0].sattDir
            }
          } else if (tit === 6 && !num) {
            if (img.length > 1) {
              return this.$message.warning('最多选择1个视频！')
            } else {
              _this.formConf.coverVideo = img[0].sattDir
            }
          }
          console.log(_this.formConf)
        },
        tit,
        'content'
      )
    },
    handleRemove() {
      this.formConf.cover = ''
    },
    // 具体日期
    onchangeTime(e) {
      console.log(this.formConf.scheduleTime)
    },
    submit(data) {
      this.$refs[data].validate((valid) => {
        if (valid) {
          this.loading = true
          console.log(this.formConf)
          let parmas = {
            id: this.id,
            expireTime: this.formConf.expireTime,
            cover: this.formConf.cover,
            coverVideo: this.formConf.coverVideo,
            title: this.formConf.name,
            name: this.formConf.name,
            scheduleTime: this.formConf.scheduleTime,
            background: this.formConf.background,
            anchors: [{
              name: this.formConf.anchorsName,
              avatar: this.formConf.anchoravatar
            }],
            assistants: [{
              name: this.formConf.assistantsname,
              avatar: this.formConf.assistantsavatar
            }],
            enableInviteReward: this.formConf.enableInviteReward,
            ruleList: this.ruleList
          }
          console.log('提交信息', parmas)
          getmeizhiupdata(parmas).then(res => {
            this.loading = false
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            this.$router.push({ path: '/marketing/mplivelist/room' })
          }).catch(res => {
            this.loading = false
          })
        }
      })
    },
    // 获取表单详情
    getFormInfo() {
      this.loading = true
      getmeizhiInfo(this.id)
        .then((res) => {
          this.loading = false
          console.log(res)
          this.id = res.id
          this.formConf = {
            name: res.name,
            background: res.background,
            cover: res.cover,
            expireTime: res.expireTime,
            scheduleTime: res.scheduleTime,
            anchorsName: res.anchors[0].name,
            anchoravatar: res.anchors[0].avatar,
            assistantsname: res.assistants ? res.assistants[0].name : '',
            assistantsavatar: res.assistants ? res.assistants[0].avatar : ''
          }
        })
        .catch((res) => {
          this.loading = false
        })
    }
  }
}
</script>

<style lang="scss" scope>
.labeltop {
  .el-input-number--small {
    /*width: 172px !important;*/
    min-width: 132px !important;
  }
}

.proCoupon {
  .el-form-item__content {
    margin-top: 5px;
  }
}

.tabPic {
  width: 40px !important;
  height: 40px !important;

  img {
    width: 100%;
    height: 100%;
  }
}

.noLeft {
  .el-form-item__content {
    margin-left: 0 !important;
  }
}

.tabNumWidth {
  .el-input-number--medium {
    width: 121px !important;
  }

  .el-input-number__increase {
    width: 20px !important;
    font-size: 12px !important;
  }

  .el-input-number__decrease {
    width: 20px !important;
    font-size: 12px !important;
  }

  .el-input-number--medium .el-input__inner {
    padding-left: 25px !important;
    padding-right: 25px !important;
  }

  thead {
    line-height: normal !important;
  }

  .el-table .cell {
    line-height: normal !important;
  }
}

.selWidth {
  width: 80%;
}

.selWidthd {
  width: 300px;
}

.button-new-tag {
  height: 28px;
  line-height: 26px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 10px;
  position: relative;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }

  video {
    width: 100%;
    height: 100%;
  }
}

.btndel {
  position: absolute;
  z-index: 1;
  width: 20px !important;
  height: 20px !important;
  left: 46px;
  top: -4px;
}

.labeltop {
  .el-form-item__label {
    /*float: none !important;*/
    /*display: inline-block !important;*/
    /*margin-left: 120px !important;*/
    /*width: auto !important;*/
  }
}

.submission {
  margin-left: 20px;
}

.inviteReward-rule > div {
  display: flex;
  flex-wrap: wrap;

  & > .el-input {
    width: 140px;
    margin-right: 10px;
  }
}

.rewardList {
  width: 900px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  span {
    margin-left: 10px;
  }
}
</style>
